package com.gitee.ywj1352.delegate;

import com.gitee.ywj1352.delegate.controller.MemberAction;
import com.gitee.ywj1352.delegate.controller.OrderAction;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wenjie.yang on 3/27/2019.
 */
public class ServletDispatch {

  public ServletDispatch() throws Exception{
    Handler handler = new Handler();
    Class<?> clazz = MemberAction.class;
    handler.setController(clazz.newInstance());
    handler.setMethod(clazz.getMethod("getMemberById"));
    handler.setUrl("/api/m");
    Handler handler2 = new Handler();
    Class<?> clazz2 = OrderAction.class;
    handler2.setController(clazz2.newInstance());
    handler2.setMethod(clazz2.getMethod("getOrderById"));
    handler2.setUrl("/api/o");
    this.handlerMapping.add(handler);
  }
  private  List<Handler> handlerMapping = new ArrayList<Handler>();
  public void doServlet(HttpServletRequest request,HttpServletResponse response)
      throws InvocationTargetException, IllegalAccessException, IOException {
    doDispatch(request,response);
  }

  private void doDispatch(HttpServletRequest request,HttpServletResponse response)
      throws InvocationTargetException, IllegalAccessException, IOException {
    //1.获取用户请求的url
    String uri = request.getRequestURI();

    //2.如果按照 J2EE 的标准 每个url 对应 servlet url 由浏览器输入
    // 根据用户的请求url 去找到这个url对应的java类的方法

    //3.通过拿到的url去handlerMapping (认为是策略常量)
    Handler handler = null;
    for (Handler h :handlerMapping){
      if(h.getUrl().equals(uri)){
        handler = h;
        break;
      }
    }
    //4.通过反射调用其对应方法 就是把任务分发给具体的 Method
    Object invoke = handler.getMethod().invoke(handler.getController(), request.getParameter("mid"));
    //dispatch 就是把method 执行结果 返回给Response
    response.getWriter().print(invoke.toString());
  }



  class Handler{
    private Object controller;

    private Method method;

    private String  url;

    public Object getController() {
      return controller;
    }

    public void setController(Object controller) {
      this.controller = controller;
    }

    public Method getMethod() {
      return method;
    }

    public void setMethod(Method method)  {
      this.method = method;
    }

    public String getUrl() {
      return url;
    }

    public void setUrl(String url) {
      this.url = url;
    }
  }



}
